package com.toaa.crazymath;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;

import com.startapp.android.publish.StartAppAd.AdMode;

public class AlarmReceiver extends BroadcastReceiver {

	public static final String TAG = AlarmReceiver.class.getSimpleName();
	private Handler mHandler = new Handler();

	@Override
	public void onReceive(final Context context, Intent intent) {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				Activity currentActivity = ActivityManager.getInstance().getCurrentActivityContext();
				if (currentActivity instanceof BaseAdsActivity) {
					if (currentActivity != null && !currentActivity.isFinishing()) {
						((BaseAdsActivity) currentActivity).showInterstitialAd(AdMode.AUTOMATIC);
					}
				}
			}
		});
	}

	/**
	 * Sets the alarm.
	 * 
	 * @param context
	 *            the new alarm
	 */
	public static void setAlarm(Context context) {
		Calendar calendar = Calendar.getInstance();

		AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent(context, AlarmReceiver.class);
		PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
		// Set schedule to start service.
		alarmMgr.setInexactRepeating(AlarmManager.RTC, calendar.getTimeInMillis() + Constant.TIME_TO_SHOW_ADS,
				Constant.TIME_TO_SHOW_ADS, alarmIntent);
	}

	/**
	 * If the alarm has been set, cancel it.
	 * 
	 * @param context
	 */
	public static void cancelAlarm(Context context) {
		AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent(context, AlarmReceiver.class);
		PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
		if (alarmMgr != null) {
			alarmMgr.cancel(alarmIntent);
		}
	}
}
